<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\adminapi\controller;

use app\services\message\notice\SmsService;
use crmeb\services\CacheService;
use think\facade\App;
use crmeb\utils\Captcha;
use app\services\system\admin\SystemAdminServices;
use think\facade\Cache;
use think\facade\Config;

/**
 * 后台登陆
 * Class Login
 * @package app\adminapi\controller
 */
class Login extends AuthController
{

    /**
     * Login constructor.
     * @param App $app
     * @param SystemAdminServices $services
     */
    public function __construct(App $app, SystemAdminServices $services)
    {
        parent::__construct($app);
        $this->services = $services;
    }

    protected function initialize()
    {
        // TODO: Implement initialize() method.
    }

    /**
     * 验证码
     * @return $this|\think\Response
     */
    public function captcha()
    {
        return app()->make(Captcha::class)->create();
    }

    /**
     * @return mixed
     */
    public function ajcaptcha()
    {
        $captchaType = $this->request->get('captchaType');
        return app('json')->success(aj_captcha_create($captchaType));
    }

    /**
     * 一次验证
     * @return mixed
     */
    public function ajcheck()
    {
        [$token, $pointJson, $captchaType] = $this->request->postMore([
            ['token', ''],
            ['pointJson', ''],
            ['captchaType', ''],
        ], true);
        try {
            aj_captcha_check_one($captchaType, $token, $pointJson);
            return app('json')->success();
        } catch (\Throwable $e) {
            return app('json')->fail(400336);
        }
    }

    /**
     * 登陆
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login()
    {
        [$account, $password, $key, $captchaVerification, $captchaType] = $this->request->postMore([
            'account',
            'pwd',
            ['key', ''],
            ['captchaVerification', ''],
            ['captchaType', '']
        ], true);

        if ($captchaVerification != '') {
            try {
                aj_captcha_check_two($captchaType, $captchaVerification);
            } catch (\Throwable $e) {
                return app('json')->fail(400336);
            }
        }

        if (strlen(trim($password)) < 6 || strlen(trim($password)) > 32) {
            return app('json')->fail(400762);
        }

        $this->validate(['account' => $account, 'pwd' => $password], \app\adminapi\validate\setting\SystemAdminValidata::class, 'get');
        $result = $this->services->login($account, $password, 'admin', $key);
        if (!$result) {
            $num = CacheService::get('login_captcha', 1);
            if ($num > 1) {
                return app('json')->fail(400140, ['login_captcha' => 1]);
            }
            CacheService::set('login_captcha', $num + 1, 60);
            return app('json')->fail(400140, ['login_captcha' => 0]);
        }
        CacheService::delete('login_captcha');
        return app('json')->success($result);
    }

    /**
     * 获取后台登录页轮播图以及LOGO
     * @return mixed
     */
    public function info()
    {
        return app('json')->success($this->services->getLoginInfo());
    }


    public function verify()
    {
        [$phone, $type] = $this->request->postMore([
            ['phone', 0],
            ['type', 'CN'],
        ], true);

        $nowKey = 'sms.admin.' . date('YmdHi');

        $total = 1;
        if (Cache::has($nowKey)) {
            $total = Cache::get($nowKey);
            if ($total > Config::get('sms.maxMinuteCount', 20))
                return app('json')->success(410006);
        }

        $time = sys_config('verify_expire_time', 1);

        try {
            $smsCode = $this->services->verify((new SmsService()), $phone, $time, app()->request->ip(), $type);
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
        }

        if ($smsCode) {
            CacheService::set('code_' . $phone, $smsCode, $time * 60);
            Cache::set($nowKey, $total, 61);
            return app('json')->success(410007, ['code' => $smsCode]);
        } else {
            return app('json')->fail(410008);
        }
    }

    public function reset_pwd()
    {
        [$account, $captcha, $phone, $pwd, $conf_pwd] = $this->request->postMore([['account', ''], ['captcha', ''], ['phone', ''], ['pwd', ''], ['conf_pwd', '']], true);

        if (!$phone) {
            return app('json')->fail(400132);
        }

        $admin = $this->services->accountByAdmin($account);
        if (!$admin) {
            return app('json')->fail(400594);
        }

        if ($admin->phone != $phone) {
            return app('json')->fail(30001);
        }

        $verifyCode = CacheService::get('code_' . $phone);
        if (!$verifyCode)
            return app('json')->fail(410009);
        $verifyCode = substr($verifyCode, 0, 6);
        if ($verifyCode != $captcha) {
            return app('json')->fail(410010);
        }

        if (strlen(trim($pwd)) < 6 || strlen(trim($pwd)) > 32) {
            return app('json')->fail(400762);
        }
        if ($pwd != $conf_pwd) {
            return app('json')->fail(400264);
        }

        // 修改账号密码
        $res = $this->services->save($admin->id, ['pwd' => $pwd, 'conf_pwd' =>  $conf_pwd, 'status' =>  $admin->status]);

        if ($res) {
            return app('json')->success(100014);
        } else {
            return app('json')->fail(100015);
        }
    }

    public function modify_pwd()
    {

        $adminInfo = $this->request->adminInfo();

        [$origin_pwd, $pwd, $conf_pwd] = $this->request->postMore([['origin_pwd', ''], ['pwd', ''], ['conf_pwd', '']], true);

        $admin = $this->services->accountByAdmin($adminInfo['account'] ?? '');
        if (!$admin) {
            return app('json')->fail(400594);
        }

        if (!$origin_pwd) {
            return app('json')->fail(400597);
        }
        if (!password_verify($origin_pwd, $admin->pwd)) {
            return app('json')->fail(400597);
        }

        $res = $this->services->save($admin->id, ['pwd' =>  $pwd, 'conf_pwd' => $conf_pwd, 'status' =>$admin->status]);

        if ($res) {
            return app('json')->success(100014);
        } else {
            return app('json')->fail(100015);
        }
    }
}
